/*
 * Copyright 2010 Alexey Romensky
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

/*
 * User: Alexey Romensky
 * Date: 20.02.2010
 * Time: 22:10:08
 */
package com.googlecode.gwt.logging.base.client;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.googlecode.gwt.logging.api.client.LogData;
import com.googlecode.gwt.logging.base.client.util.Level;
import org.slf4j.Marker;

import java.util.Date;

import static com.googlecode.gwt.logging.base.client.util.Level.FATAL;
import static com.googlecode.gwt.logging.base.client.util.LogUtil.getContext;
import static com.googlecode.gwt.logging.base.client.util.LogUtil.stackTraceToString;

public class FatalLogWriter extends OffLogWriter {

    private static final DateTimeFormat DATE_TIME_FORMAT = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss.SSS z");

    private final Appender appender;

    public FatalLogWriter(Appender appender) {
        this.appender = appender;
    }

    @Override
    public boolean isFatalEnabled(Marker marker) {
        return true;
    }

    @Override
    public void fatal(LogData data) {
        log(FATAL, data);
    }

    @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
    protected void log(Level level, LogData data) {

        final String callerFileName = data.getCallerFileName();
        final StackTraceElement stackTraceElement = getContext(callerFileName);

        final StringBuilder sb = new StringBuilder();
        sb.append('[').append(DATE_TIME_FORMAT.format(new Date())).append("] ");
        sb.append(level.getLogLabel()).append(": ").append(data.getMessage());

        if (stackTraceElement == null) {
            sb.append('\n');
        } else {
            sb.append(" (").append(stackTraceElement.getFileName()).append(':');
            sb.append(stackTraceElement.getLineNumber()).append(")\n");
        }

        stackTraceToString(sb, data.getThrowable());

        final String text = sb.toString();
        appender.append(level, text);
    }
}
